package com.wangjw.coreTechnology;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;

/**
 * Created by wangjw on 18/7/17.
 */
public class NIO2Server {

    public static void main(String[] args) throws IOException {
        AsynchronousServerSocketChannel serverSocket =
                AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(InetAddress.getLocalHost(), 8887));
        serverSocket.accept(serverSocket, new CompletionHandler<AsynchronousSocketChannel, AsynchronousServerSocketChannel>() { // 为异步操作指定 CompletionHandler 回调函数
            @Override
            public void completed(AsynchronousSocketChannel socketChannel, AsynchronousServerSocketChannel serverSocketChannel) {
                serverSocketChannel.accept(serverSocketChannel, this);
                socketChannel.write(Charset.defaultCharset().encode("Hello World!"));
            }

            @Override
            public void failed(Throwable exc, AsynchronousServerSocketChannel attachment) {

            }
        });
    }
}
